package tv.drplay.course

import android.app.ActivityManager
import android.content.Context
import com.danikula.videocache.HttpProxyCacheServer
import top.kpromise.ibase.IApplication
import top.kpromise.utils.ILog
import top.kpromise.utils.RegularUtils
import tv.drplay.course.utils.*

class MoWanApplication :IApplication() {

    override fun onCreate() {
        super.onCreate()
        if (packageName == currentProcessName()) {
            ILog.e("===init===", "init for application...")
            app = this
            initForApp()
        }
        // initPush()
    }

    private fun currentProcessName(): String? {
        val pid = android.os.Process.myPid()
        val mActivityManager = app?.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
        mActivityManager ?: return null
        for (appProcess in mActivityManager.runningAppProcesses) {
            if (appProcess.pid == pid) {
                return appProcess.processName
            }
        }
        return null
    }

    private var proxy: HttpProxyCacheServer? = null

    private fun newProxy(): HttpProxyCacheServer {
        val maxSize = 3L * 1024 * 1024 * 1024
        return HttpProxyCacheServer.Builder(this)
            .maxCacheFilesCount(100)
            .maxCacheSize(maxSize)       // 3 Gb for cache
            .build()
    }

    companion object {
        private fun getProxy(): HttpProxyCacheServer? {
            val app = app as? MoWanApplication?
            app ?: return null
            val proxy = app.proxy ?: app.newProxy()
            app.proxy = proxy
            return proxy
        }

        fun getProxyUrl(url: String?): String? {
            if (!RegularUtils.isUrl(url)) return url
            return getProxy()?.getProxyUrl(url)
        }
    }

    private fun initForApp() {
        initHttp()
        initCoreData()
        initSentrySdk(this)
        initBaiduAnalytics()
        initShortCuts(this)
        initImageLoader()
        //initThirdSdk()
    }
}